<template>
    <div class="filesDetails">
        <el-table :data="detalisList" v-loading="loading" @row-click="row" @row-contextmenu="contextmenu"
            @row-dblclick="dblclick" @contextmenu.prevent="rightClick" style="width: 100%" height="86vh">
            <el-table-column prop="Title" :label="$t('main.fileTitle')">
                <template v-slot="title">
                    <div class="flex aic">
                        <i v-if="title.row.isfolder == 0" class="iconfont icon-bumen"
                            style="color: #646464;font-size:18px "></i>
                        <i v-else-if="title.row.isfolder == 1" class="iconfont icon-wenjianleixing-suolvetu-wenjianjia"
                            style="color: #646464;font-size: 18px;"></i>
                        <img v-else-if="title.row.file_or_folder_name.split('.')[1] == 'jpg' || title.row.file_or_folder_name.split('.')[1] == 'png'"
                            class="titleImg" :src="title.row.file_path" alt="">
                        <i v-else-if="title.row.file_or_folder_name.split('.')[1] == 'pdf'"
                            class="ml-5 mr-5 iconfont icon-pdf" style="font-size: 22px;"></i>
                        <i v-else-if="title.row.file_or_folder_name.split('.')[1] == 'mp4'"
                            class="ml-5 mr-5 iconfont icon-shipin" style="font-size: 23px;"></i>
                        <i v-else-if="title.row.file_or_folder_name.split('.')[1] == 'txt'"
                            class="ml-5 mr-5 iconfont icon-wenben" style="font-size: 24px;"></i>
                        <i v-else class="ml-5 iconfont icon-qitawenjian" style="font-size: 27px;"></i>
                        <span class="ml-20">{{ title.row.file_or_folder_name }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="size" :label="$t('main.fileSize')" />
            <el-table-column prop="upload_time" :label="$t('main.fileDate')" sortable :formatter="formatter" />
        </el-table>
        <!-- 图片预览 -->
        <el-dialog v-model="preview" title="图片预览">
            <div class="flex aic jc-sb ">
                <!-- <p disabled class="iconfont icon-xiangzuojiantou fwb cp" @click="back"></p> -->
                <el-button @click="back" :disabled="!backState" class="iconfont icon-xiangzuojiantou fwb" circle />
                <img class="w90p" :src="fileUrl" alt="" style="height: 450px;">
                <el-button @click="pageDown" :disabled="!pageDownState" class="iconfont icon-xiangyoujiantou fwb" circle />
                <!-- <p class="iconfont icon-xiangyoujiantou fwb cp" @click="pageDown"></p> -->
            </div>
        </el-dialog>
        <!-- 文件上传 -->
        <!-- <div class="state pl-10 pr-10" v-show="state || download">{{ state ? 'Are uploading' : 'Download progress' }}:<span
                class="ml-5">{{ state ? tempo : percent }}%</span></div> -->
        <el-progress class="state" v-show="state" :percentage="tempo" status="success" :stroke-width="3"
            :text-inside="true" /> <!-- 上传进度 -->
        <el-progress class="state" v-show="download" :percentage="percent" :stroke-width="3"
            :text-inside="true" /><!-- 下载进度 -->

        <el-upload v-show="isRight" class="upload-demo" action="http://d-api.files99.com/qmapi/file/input"
            :on-success="handleChange" :on-progress="progress" :on-error="error" :show-file-list="false" :data="data">
            <el-button circle type="primary" size="large" class="add">+</el-button>
        </el-upload>
        <!-- 分享 -->
        <el-dialog v-model="dialogVisible" title="文件分享" width="30%" :before-close="handleClose">
            <div v-if="create">
                <p>文件名：{{ name }}</p>
                <el-radio-group v-model="radio" class="ml-4">
                    <el-radio label="0" size="large">无需密码</el-radio>
                    <el-radio label="1" size="large">通过密码分享</el-radio>
                </el-radio-group>
                <div class="flex aic jc-sb mb-10">
                    <p>到期时间：{{ time }}</p>
                    <el-select v-model="selectDate" @change="selectTime" class="m-2" placeholder="Select">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
                <div v-if="radio == '1'" class="flex aic">
                    <p>密码：</p>
                    <el-input v-model="password" placeholder="请设置密码" style="width: 90%;"></el-input>
                </div>
            </div>
            <div v-else>
                <div>
                    <div class="flex aic">
                        <p class="w13p">链 接：&nbsp;</p>
                        <span>{{ shareLink }}</span>
                    </div>
                    <div v-if="radio == '1'" class="flex aic mt-10">
                        <p class="w13p">提取码：</p>
                        <span>{{ password }}</span>
                    </div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">Cancel</el-button>
                    <el-button v-if="create" type="primary" @click="share">
                        创建链接
                    </el-button>
                    <el-button v-else type="primary" @click="copy">
                        复制并关闭
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 创建文件夹 -->
        <el-dialog v-model="mkdir" @opened="createDialog" title="新建文件夹" width="30%" align-center>
            <div class="flex aic">
                <i class="iconfont icon-24gl-folderPlus mr-5" style="font-size: 24px;"></i>
                <el-input v-model="fileName" ref="refCreate" @keyup.enter="enter" placeholder=""></el-input>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="mkdir = false">Cancel</el-button>
                    <el-button type="primary" @click="addFolder">
                        Confirm
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as $axios from '../../../api/index'
import axios from 'axios';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { menusEvent } from 'vue3-menus';  //鼠标右键功能菜单
import useClipboard from 'vue-clipboard3';
import { useDemoStore } from '../../../pinia/index'
const store = useDemoStore()
const { toClipboard } = useClipboard(); //剪切板
const props = defineProps({
    detalisList: Array,
    userId: String,
    user_id: Array,
    inquiryId: String,
    orderId: String,
    clientId: String,
    sendId: String,
    payId: String,
    path: String,
    md5: String,
    menuActivate: Boolean
})

//加载
const loading = ref(false)

// 开启加载
const openLoading = () => {
    loading.value = true
}
// 关闭加载
const shutLoading = () => {
    loading.value = false
}

// 排序
// const formatter = (row, column) => {
//     // console.log(row)
//     return row.address
// }


// 当列表某一行被点击时会触发该事件
const pathList = ref([''])
const path = ref('')
const filePath = ref('')
const id = ref('')
const arrs = ref([])
const storeValue = ref({})
const storeName = ref({})
const send = ref()
const filesId = ref('')
const row = (value) => {
    storeValue.value = value || storeValue.value
    // console.log(storeValue.value)
    if (storeValue.value.send == "no") {
        props.detalisList.forEach(item => {
            if (item.UserGroupName == storeValue.value.UserGroupName) {
                arrs.value = storeValue.value
                emits('userList', item.user)
                pathList.value.push(storeValue.value)
                // console.log(item.user)
            }
        })
    } else if (storeValue.value.send == "yes" || storeValue.value.isfolder == 1) {
        // console.log(storeValue.value)
        storeValue.value.send == "yes" ? storeName.value = storeValue.value : ''
        path.value = storeValue.value.send == undefined ? storeValue.value.file_or_folder_name : ''
        filePath.value = storeValue.value.send == undefined ? storeValue.value.file_path : ''
        id.value = storeValue.value.id || storeValue.value.user_id || id.value
        filesId.value = storeValue.value.files_id
        data.value.path = path.value //直接更改上传参数
        data.value.md5 = filePath.value //直接更改上传参数
        data.value.user_open_id = id.value //直接更改上传参数
        pathList.value.push(storeValue.value)
        getTable()
    }
    // debugger
    send.value = value.send
    console.log(value)
    emits('crumbs', pathList.value)

}

const clearPath = () => {
    path.value = ''  //清空path
    filePath.value = ''
}

// 当列表某一行被双击时会触发该事件
const preview = ref(false)
const switchId = ref({})
const fileUrl = ref('')
const dblclick = (row) => {
    backState.value = true
    pageDownState.value = true
    // console.log(row)
    if (row.isfolder != 1) {
        const splitArr = row.file_path.split('.')
        const fileType = splitArr[splitArr.length - 1]
        if (fileType == 'jpeg' || fileType == 'png' || fileType == 'jpg') {
            preview.value = true
            const data = {
                token: store.token,
                image_id: row.files_id
            }
            $axios.$fileGet_now_image(data).then(res => {
                fileUrl.value = res.data.file_path
                switchId.value = res.data
                // console.log(res.data)
            })
        } else {
            open(row.file_path)
        }
        //  else {
        //     ElMessage({
        //         message: '该类型不支持预览',
        //         type: 'warning',
        //     })
        // }
    }
}

// 上一页
const backState = ref(true)
const back = () => {
    pageDownState.value = true
    const data = {
        token: store.token,
        path: path.value,
        inquiry_id: props.inquiryId,
        product_id: switchId.value.product_id,
        order_id: props.orderId,
        customer_id: props.clientId,
        task_id: props.sendId,
        bbs_id: switchId.value.bbs_id,
        Payment_id: props.payId,
        user_open_id: switchId.value.user_id,
        image_id: switchId.value.files_id,
        type: "back"
    }
    $axios.$fileGet_next_file(data).then(res => {
        // console.log(res.data)
        if (res.data.hasLast != true) {
            switchId.value = res.data
            fileUrl.value = res.data.file_path
        } else {
            backState.value = false
        }
    })
}
// 下一页
const pageDownState = ref(true)
const pageDown = () => {
    backState.value = true
    const data = {
        token: store.token,
        path: path.value,
        inquiry_id: props.inquiryId,
        product_id: switchId.value.product_id,
        order_id: props.orderId,
        customer_id: props.clientId,
        task_id: props.sendId,
        bbs_id: switchId.value.bbs_id,
        Payment_id: props.payId,
        user_open_id: switchId.value.user_id,
        image_id: switchId.value.files_id,
        type: "next"
    }
    $axios.$fileGet_next_file(data).then(res => {
        console.log(res.data)
        if (res.data.hasLast != true) {
            switchId.value = res.data
            fileUrl.value = res.data.file_path
        } else {
            pageDownState.value = false
        }
    })
}


const clear = () => {
    pathList.value = ['']  //展开菜单就清空数组
}

// 文件数据
const flieData = ref([])
const isRight = ref(false)
const getTable = (name, fileMd5, fileId) => {
    loading.value = true
    const data = {
        token: store.token,
        user_open_id: props.userId || id.value,
        path: name == '' ? '' : name || path.value,
        md5: fileMd5 || filePath.value,
        files_id: fileId || filesId.value,
        inquiry_id: props.inquiryId,
        order_id: props.orderId,
        customer_id: props.clientId,
        task_id: props.sendId,
        Payment_id: props.payId
    }
    $axios.$fileGet(data).then(res => {
        loading.value = false
        // console.log(res.data)
        flieData.value = res.data
        isRight.value = true
        emits('getTotal', res.data.length)
        emits('userList', res.data)
    })
}

// 清空数据
const clearSend = () => {
    // send.value = ''
    // filesId.value = ''
    // isfolder.value = false
    isRight.value = false
}

// 菜单激活改变状态
const changeRight = () => {
    isRight.value = true
}

// 鼠标右键触发
const file_path = ref() //下载链接
const name = ref()  //文件名称
const isfolder = ref(false)  //文件类别
const files_id = ref()  //文件id
const user_id = ref('') //user_id
const isDel = ref(false)
const contextmenu = (value) => {
    file_path.value = value.file_path
    name.value = value.file_or_folder_name
    files_id.value = value.files_id
    user_id.value = value.user_id
    isfolder.value = value.isfolder == 1 ? false : true
    isDel.value = true
    console.log(value)
}

// 右键触发，弹出菜单
const rightClick = (event) => {
    // console.log(isRight.value)
    // if (send.value == 'yes' || filesId.value || isfolder.value || props.inquiryId || props.orderId || props.clientId || props.sendId || props.payId) { //外面不可以右键菜单
    if (isRight.value || props.inquiryId || props.orderId || props.clientId || props.sendId || props.payId || props.menuActivate) {
        if (isDel.value) {
            menus.value.menus.forEach(item => {
                if (item.label.includes('删除')) {
                    item.disabled = false
                }
            })
            isDel.value = false
        } else {
            menus.value.menus.forEach(item => {
                if (item.label.includes('删除')) {
                    item.disabled = true
                }
            })
        }

        if (isfolder.value) {
            menus.value.menus.forEach(item => {
                if (item.label.includes('下载') || item.label.includes('分享')) {
                    item.disabled = false
                }
            })
            isfolder.value = false
        } else {
            menus.value.menus.forEach(item => {
                if (item.label.includes('下载') || item.label.includes('分享')) {
                    item.disabled = true
                }
            })
        }
        // isRight.value = false
        menusEvent(event, menus.value);
        event.preventDefault();
    }
}
const menus = ref({
    menus: [
        {
            label: "新建",
            icon: '<i class="iconfont icon-24gl-folderPlus"></i>',
            tip: '',
            // disabled: true,
            click: () => {
                mkdir.value = true
            }
        },
        {
            label: "下载",
            icon: '<i class="iconfont icon-xiazai"></i>',
            tip: ' ',
            disabled: true,
            click: () => {
                down()
            }
        },
        {
            label: "分享",
            icon: '<i class="iconfont icon-fenxiang"></i>',
            tip: '',
            disabled: true,
            click: () => {
                dialogVisible.value = true
                create.value = true
                selectTime()
            }
        },
        {
            label: "删除",
            icon: '<i class="iconfont icon-shanchu"></i>',
            tip: '',
            disabled: true,
            click: () => {
                fileDel()
            }
        },
    ]
});

// 下载文件
const percent = ref('')
const download = ref(false)
const down = () => {
    ElNotification({
        // title: 'Success',
        message: 'Download Start',
        type: 'success',
        duration: 2000
    })
    const data = {
        token: store.token,
        file: files_id.value,
        type: store.type == 4 ? 'FileModel' : 'FileCustomer'
    }
    axios({
        url: 'http://d-api.files99.com/qmapi/file/down',
        method: 'post',
        data: data,
        onDownloadProgress: (progressEvent) => { //获取下载进度
            download.value = true
            let process = (progressEvent.loaded / progressEvent.total * 100 | 0)
            percent.value = process
            process == 100 || process == 0 ? download.value = false : ''
        }
    }).then(res => {
        if (res.data.Status == 0) {
            ElMessage({
                message: 'Download successful',
                type: 'success',
            })
            var base64 = res.data.data.base.toString(); // res.data.data.base 就是base64哈
            var byteCharacters = atob(
                base64.replace(/^data:image\/(png|jpeg|jpg);base64,/, "")
            );
            var byteNumbers = new Array(byteCharacters.length);
            for (var i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            var blob = new Blob([byteArray], {
                type: undefined,
            });
            var aLink = document.createElement("a");
            aLink.download = name.value; //这里写保存时的图片名称
            aLink.href = URL.createObjectURL(blob);
            aLink.click();
        } else {
            ElMessage({
                message: 'Download failed',
                type: 'warning',
            })
        }
    })
}

// 创建文件夹的对话框
const refCreate = ref()
const createDialog = () => {
    refCreate.value.focus()  //获取输入框焦点
}

// 回车触发
const enter = () => {
    addFolder()
}

// 创建文件夹
const fileName = ref('新建文件夹')
const mkdir = ref(false)
let startTime = Date.now();
const addFolder = () => {
    const data = {
        token: store.token,
        path: path.value || props.path || '',
        md5: filePath.value || props.md5 || '',
        user_open_id: props.userId || id.value || '',
        name: fileName.value || '',
        inquiry_id: props.inquiryId,
        order_id: props.orderId,
        customer_id: props.clientId,
        task_id: props.sendId,
        Payment_id: props.payId
    }
    console.log(data)
    let endTime = Date.now();  //节流，避免提交多次
    if (endTime - startTime > 400) {
        $axios.$fileNew(data).then(res => {
            // console.log(res)
            if (res.Status == 0) {
                emits('newFile', res.data)
                // getTable()
                mkdir.value = false
                fileName.value = '新建文件夹'
                ElMessage({
                    message: 'Created successfully',
                    type: 'success',
                })
            }
        })
        startTime = endTime;
    }
}

// 分享弹窗
const dialogVisible = ref(false)
// 单选框
const radio = ref('0')

// 到期时间
const time = ref()
// 设置过期时间
const selectDate = ref(1)
const options = [
    {
        label: '一小时过期',
        value: 1
    },
    {
        label: '一周过期',
        value: 2
    },
    {
        label: '一个月过期',
        value: 3
    },
    {
        label: '半年过期',
        value: 4
    },
    {
        label: '一年过期',
        value: 5
    },
]
// 获取过期时间
const selectTime = (value) => {
    const data = {
        token: store.token,
        type: value || 1
    }
    $axios.$fileGet_time(data).then(res => {
        time.value = res.data.time
        // console.log(res.data)
    })
}

watch(radio, (value) => {
    if (value == 1) {
        random(1000, 9000)
    } else {
        password.value = ''
    }
})

// 提取码输入框
const password = ref('')
function random(num1, num2) {  //生成随机数
    var text = Math.random() * (num2 - num1) + num1
    password.value = Math.round(text)
}

// 分享按钮
const create = ref(true)
const shareLink = ref() //分享链接
const share = () => {
    const data = {
        token: store.token,
        path: name.value,
        files_id: files_id.value,
        expiration_time: time.value,
        pwd: password.value
    }
    if (radio.value == '0') {  //正常分享
        $axios.$fileShare(data).then(res => {
            if (res.Status == 0) {
                create.value = false
                shareLink.value = res.data.share_customer
                console.log(res)
            }
        })
    } else {  //通过密码分享
        $axios.$filePassword_share(data).then(res => {
            if (res.Status == 0) {
                create.value = false
                shareLink.value = res.data.share_customer
                console.log(res)
            }
        })
    }
}

// 复制并关闭
const copy = async () => {
    dialogVisible.value = false
    const pas = password.value ? '提取码:' + password.value : ''
    try {
        await toClipboard('链接：' + shareLink.value + ' ' + pas)
    } catch (e) {
        console.error(e)
    }
    ElMessage({
        message: 'Copy success',
        type: 'success',
    })
}

// 删除文件
const fileDel = () => {
    ElMessageBox.confirm(
        'The file will be permanently deleted. Are you sure?',
        'Warning',
        {
            confirmButtonText: 'Confirm',
            cancelButtonText: 'Cancel',
            type: 'warning',
            center: true
        }
    ).then(() => {
        const data = {
            token: store.token,
            file_ids: files_id.value,
            user_open_id: user_id.value || id.value
        }
        $axios.$fileDel(data).then(res => {
            if (res.Status == 0) {
                emits('fileDel', files_id.value)
                ElMessage({
                    message: 'Delete the success',
                    type: 'success',
                })
            }
        })
    })
}

// 更改上传参数
const changeFile = (name, filePath) => {
    // console.log(path)
    data.value.path = name
    data.value.md5 = filePath
}


// 文件上传参数
const data = ref({
    token: store.token,
    path: path.value,
    md5: filePath.value,
    user_open_id: id.value,
    inquiry_id: props.inquiryId,
    order_id: props.orderId,
    customer_id: props.clientId,
    task_id: props.sendId,
    Payment_id: props.payId
})

// 上传时执行的钩子
const state = ref(false)
const tempo = ref('')
const progress = (value) => {
    tempo.value = value.percent
    state.value = true
    // console.log(value.percent)
}

// 上传成功执行的钩子
const handleChange = (value) => {
    state.value = false
    if (value.Status == 0) {
        // getTable()
        emits('newFile', value.data)
        ElMessage({
            message: 'upload successful',
            type: 'success',
        })
    } else {
        ElMessage({
            message: 'Upload failed',
            type: 'warning',
        })
    }
    // console.log(value)
}

// 上传失败执行的钩子
const error = (value) => {
    state.value = false
    ElMessage({
        message: 'Upload failed',
        type: 'warning',
    })
}

const emits = defineEmits(['userList', 'crumbs', 'getTotal', 'fileDel', 'newFile'])
defineExpose({  //暴露方法
    clear,
    row,
    getTable,
    clearPath,
    clearSend,
    changeRight,
    openLoading,
    shutLoading,
    changeFile,
    arrs,
    isRight,
    storeName
})

</script>

<style lang="less" scoped>
@import '../files.less';

.brs {
    border-radius: 10px;
}
</style>